package com.android.infantschool.ui.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.CardView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.infantschool.R;
import com.android.infantschool.bean.AppUpdateBean;
import com.android.infantschool.bean.AuthCodeBean;
import com.android.infantschool.bean.BaseBean;
import com.android.infantschool.bean.LoginBean;
import com.android.infantschool.model.config.AppConfig;
import com.android.infantschool.model.http.XUtilsManager;
import com.android.infantschool.model.mvp.presenter.AppUpdatePresenter;
import com.android.infantschool.model.mvp.presenter.AppUpdatePresenterImpl;
import com.android.infantschool.model.mvp.presenter.AuthCodePresenter;
import com.android.infantschool.model.mvp.presenter.AuthCodePresenterImpl;
import com.android.infantschool.model.mvp.presenter.HomeBannerPresenter;
import com.android.infantschool.model.mvp.presenter.HomeBannerPresenterImpl;
import com.android.infantschool.model.mvp.presenter.LoginPresenter;
import com.android.infantschool.model.mvp.presenter.LoginPresenterImpl;
import com.android.infantschool.model.mvp.view.AppUpdateView;
import com.android.infantschool.model.mvp.view.AuthCodeView;
import com.android.infantschool.model.mvp.view.HomeBannerView;
import com.android.infantschool.model.mvp.view.LoginView;
import com.android.infantschool.ui.dialog.DialogAppUpdate;
import com.android.infantschool.ui.dialog.DialogVersion;
import com.android.infantschool.util.Constant;
import com.android.infantschool.util.SystemUtil;
import com.android.infantschool.util.ToastUtil;
import com.android.infantschool.util.ZhengZe;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.helper.Logger;

/**
 * @author Administrator
 * @particulars
 * @time 2019\6\18 0018 10:19
 * @class describe
 */
public class LoginActivity extends BaseActivity implements AuthCodeView, LoginView {

    @BindView(R.id.btn_login)
    public Button btnLogin;
    @BindView(R.id.ed_user_phone)
    public EditText edUserPhone;
    @BindView(R.id.ed_user_password)
    public EditText edUserPassword;
    @BindView(R.id.tv_forget_psw)
    public TextView tvForgetPsw;
    @BindView(R.id.img_header)
    public ImageView imgHeader;
    @BindView(R.id.tv_auth_code)
    public TextView tvAuthCode;
    @BindView(R.id.card_user_password)
    public CardView cardUserPassword;
    @BindView(R.id.ed_phone_code)
    public EditText edPhoneCode;
    @BindView(R.id.btn_get_code)
    public Button btnGetCode;
    @BindView(R.id.card_user_auth_code)
    public CardView cardUserAuthCode;

    private CountDownTimer countDownTimer = null;
    private int loginType = 1;//默认账号密码登录,1:密码登录,2:验证码登录

    public static Intent newIntent(Activity activity) {
        Intent intent = new Intent(activity, LoginActivity.class);
        return intent;
    }

    private LoginPresenter loginPresenter;
    private AuthCodePresenter authCodePresenter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        loginPresenter = new LoginPresenterImpl(this);
        authCodePresenter = new AuthCodePresenterImpl(this);
        if (AppConfig.getRememberPswStatus()) {
            edUserPhone.setText(AppConfig.getLoginUser());
            edUserPassword.setText(AppConfig.getLoginPsw());
            edUserPhone.setSelection(AppConfig.getLoginUser().length());
            edUserPassword.setSelection(AppConfig.getLoginPsw().length());
        } else {
            edUserPhone.setText("");
            edUserPassword.setText("");
        }
    }

    @OnClick({R.id.ed_user_phone, R.id.ed_user_password, R.id.tv_forget_psw, R.id.tv_auth_code, R.id.btn_login, R.id.btn_get_code})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_forget_psw:
                startActivity(ForgetPswActivity.newIntent(LoginActivity.this));
                break;
            case R.id.tv_auth_code:
                edPhoneCode.setText("");
                edUserPassword.setText("");
                if (loginType == 1) {
                    showAuthCode();
                } else if (loginType == 2) {
                    showLoginPsw();
                }
                break;
            case R.id.btn_get_code:
                final String phones = edUserPhone.getText().toString().trim();
                if (TextUtils.isEmpty(phones)) {
                    ToastUtil.showShortToast(this, "请输入手机号");
                    return;
                }
                if (!ZhengZe.isMobileNO(phones) || phones.length() != 11) {
                    ToastUtil.showShortToast(this, "请输入正确的手机号");
                    return;
                }
                Map<String, String> maps = new HashMap<>();
                maps.put("tel", phones);
                authCodePresenter.getAuthCode(maps);
                break;
            case R.id.btn_login:

                final String phone = edUserPhone.getText().toString().trim();
                if (TextUtils.isEmpty(phone)) {
                    ToastUtil.showShortToast(this, "请输入账号");
                    return;
                }
                if (loginType == 1) {//密码登录
                    final String psw = edUserPassword.getText().toString().trim();
                    if (TextUtils.isEmpty(psw)) {
                        ToastUtil.showShortToast(this, "请输入密码");
                        return;
                    }
                    this.showLoading();
                    Map<String, String> map = new HashMap<>();
                    map.put("username", phone);
                    map.put("password", psw);
                    map.put("role", "0");//教师为0，院长为1
                    map.put("loginType", "0");
                    Log.e(TAG, "map:" + map.toString());
                    loginPresenter.postLogin(map);
                    AppConfig.setLoginPsw(psw);
                    AppConfig.setLoginUser(phone);
                    AppConfig.setLoginType(0);
                } else if (loginType == 2) {//验证码登录
                    final String code = edPhoneCode.getText().toString().trim();
                    if (TextUtils.isEmpty(code)) {
                        ToastUtil.showShortToast(this, "请输入验证码");
                        return;
                    }
                    if (code.length() != 4) {
                        ToastUtil.showShortToast(this, "请输入正确的验证码");
                        return;
                    }

                    this.showLoading();
                    Map<String, String> map = new HashMap<>();
                    map.put("username", phone);
                    map.put("key", code);
                    map.put("role", "0");//教师为0，院长为1
                    map.put("loginType", "1");
                    Log.e(TAG, "map:" + map.toString());
                    loginPresenter.postLogin(map);
                    AppConfig.setLoginPsw(code);
                    AppConfig.setLoginUser(phone);
                    AppConfig.setLoginType(1);
                }
                break;
        }
    }

    @Override
    public void errorAuthCode(String error) {
        btnGetCode.setEnabled(true);
        ToastUtil.showShortToast(this, "网络异常:" + error);
    }

    @Override
    public void successAuthCode(BaseBean baseBean) {
        AuthCodeBean codeBean = (AuthCodeBean) baseBean;
        if (codeBean.getCode().equals("0")) {
            btnGetCode.setEnabled(false);
            if (countDownTimer != null) {
                countDownTimer.cancel();
                countDownTimer = null;
            }
            countDownTimer = new CountDownTimer(60 * 1000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    btnGetCode.setText(millisUntilFinished / 1000L + "");
                }

                @Override
                public void onFinish() {
                    btnGetCode.setText("获取验证码");
                    btnGetCode.setEnabled(true);
                }
            };
            countDownTimer.start();
        } else {
            btnGetCode.setEnabled(true);
            ToastUtil.showShortToast(this, codeBean.getMsg());
        }
    }

    @Override
    public void errorLogin(String error) {
        LoginActivity.this.dismissLoading();
        ToastUtil.showShortToast(this, "网络异常:" + error);
    }

    @Override
    public void successLogin(BaseBean baseBean) {
        LoginActivity.this.dismissLoading();
        LoginBean loginBean = (LoginBean) baseBean;
        if (loginBean.getCode().equals("0")) {
            AppConfig.setRememberPswStatus(true);
            AppConfig.setLoginStatus(true);
            AppConfig.setToken(loginBean.getData().getToken());
            AppConfig.setUserPhoto(loginBean.getData().getImg());
            AppConfig.setNickName(loginBean.getData().getUsername());
            AppConfig.setSchoolName(loginBean.getData().getKidUser());
            AppConfig.setUserPhone(loginBean.getData().getTel());
            startActivity(MainActivity.newIntent(LoginActivity.this));
            finish();
        } else {
            ToastUtil.showShortToast(this, loginBean.getMsg());
        }
    }

    private void showLoginPsw() {
        cardUserAuthCode.setVisibility(View.GONE);
        cardUserPassword.setVisibility(View.VISIBLE);
        tvAuthCode.setText("短信验证码登录");
        loginType = 1;
    }

    private void showAuthCode() {
        cardUserAuthCode.setVisibility(View.VISIBLE);
        cardUserPassword.setVisibility(View.GONE);
        tvAuthCode.setText("密码登录");
        loginType = 2;
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
        }
        if (authCodePresenter != null) {
            authCodePresenter.onDestroy();
            authCodePresenter = null;
        }
        if (loginPresenter != null) {
            loginPresenter.onDestroy();
            loginPresenter = null;
        }
    }
}